<template>
	<view class="page-container back-grey-light">
		<view class="pall-base">
			<text class="grey-light">基本信息</text>
		</view>
		<view class="prow-l pcol-l info-grid back-white">
			<text>商品图片</text>
			<view class="radius-base image-box back-white">
				<image v-if="image" class="image radius-base" :src="image" mode="aspectFill" @click="previewImage(0, [image])"></image>
				<image v-else class="image radius-base" src="/static/icon/upload.png" mode="aspectFill" @click="selectUploadHandle()"></image>
				<view v-if="image" class="row-box center radius-circle back-text-grey close-box" style="padding: 10rpx;" @click.stop="image=''">
					<u-icon name="close" color="#ffffff" size="24" :bold="true"></u-icon>
				</view>
			</view>
		</view>
		<view class="prow-l info-grid s-h back-white">
			<text>商品名称</text>
			<u-input v-model="name" type="text" :maxlength="20" placeholder="请输入商品名称(20字以内)" placeholder-style="color: #999;font-size: 26rpx;line-height: 40rpx;" />
		</view>
		<view class="prow-l info-grid s-h back-white">
			<text>商品描述</text>
			<u-input v-model="description" type="text" :maxlength="30" placeholder="请输入商品描述(选填,30字以内)" placeholder-style="color: #999;font-size: 26rpx;line-height: 40rpx;" />
		</view>
		<view class="prow-l info-grid s-h back-white">
			<text>商品分类</text>
			<view class="row-box sb" @click="goSelectGoodsCate()">
				<text v-if="cateId">{{ cateName }}</text>
				<text v-else class="grey-light">请选择分类</text>
				<u-icon name="arrow-right" :color="nomarlColor" size="28"></u-icon>
			</view>
		</view>
		<view v-if="!spLists.length">
			<view class="pall-base">
				<text class="grey-light">商品价格</text>
			</view>
			<view class="prow-l info-grid s-h back-white">
				<text>价格(元)</text>
				<u-input v-model="price" type="digit" :maxlength="10" placeholder="请输入价格" placeholder-style="color: #999;font-size: 26rpx;line-height: 40rpx;" />
			</view>
			<view class="prow-l info-grid s-h back-white">
				<text>餐盒费(元)</text>
				<u-input v-model="boxPrice" type="digit" :maxlength="10" placeholder="请输入餐盒费" placeholder-style="color: #999;font-size: 26rpx;line-height: 40rpx;" />
			</view>
		</view>
		<view class="pall-base">
			<text class="grey-light">商品规格(如小份,大份)</text>
		</view>
		<view v-if="!spLists.length" class="prow-l row-box back-white s-h" @click="goSpecManage()">
			<u-icon name="plus-circle" :color="primaryColor" size="40"></u-icon>
			<text class="ml-10 primary">添加多规格(选填)</text>
		</view>
		<view v-else>
			<view v-for="(item, index) in spLists" :key="index" class="prow-l row-box back-white s-h bb">
					<text class="s24" style="margin-right: 40rpx;">{{ item.name }}</text>
					<text class="s24" style="margin-right: 40rpx;">{{ item.price }}元</text>
					<text class="s24 grey-light mr-base">餐盒费：{{ item.boxPrice }}元</text>
			</view>
			<view class="prow-l row-box center back-white s-h" @click="goSpecManage()">
				<u-icon name="edit-pen-fill" :color="primaryColor" :size="36"
					label='管理商品规格' label-size="26" label-pos="right" :label-color="primaryColor" margin-left="4">
				</u-icon>
			</view>
		</view>
		<view class="pall-base">
			<text class="grey-light">商品属性(如微辣,中辣,特辣)</text>
		</view>
		<view v-if="!attLists.length" class="prow-l row-box back-white s-h" @click="goAttrManage()">
			<u-icon name="plus-circle" :color="primaryColor" size="40"></u-icon>
			<text class="ml-10 primary">添加属性(选填)</text>
		</view>
		<view v-else>
			<view v-for="(item, index) in attLists" :key="index" class="prow-l pcol-l col-box back-white bb">
				<text class="s24 mb-base">{{ item.name }}</text>
				<view style="display: flex;flex-wrap: wrap;">
					<view v-for="(item2, index2) in item.attrItemList" :key="index2"
						class="radius-l back-grey mr-base" style="padding: 6rpx 20rpx;">
						<text class="s24">{{ item2.name }}</text>
					</view>
				</view>
			</view>
			<view class="prow-l row-box center back-white s-h" @click="goAttrManage()">
				<u-icon name="edit-pen-fill" :color="primaryColor" :size="36"
					label='管理商品属性' label-size="26" label-pos="right" :label-color="primaryColor" margin-left="4">
				</u-icon>
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view class="submit-button-box">
			<view class="submit-button back-primary" @click="submitHandle()">保存</view>
		</view>
	</view>
</template>

<script>
	import env from '@/utils/env.js'
	export default {
		data() {
			return {
				qntoken: '',  // 七牛云上传token
				type: 0, // 新增0 修改1
				id: '', // 如果是修改，商品id
				
				last: '', // 回显的图片临时地址
				image: '', // 图片临时地址
				upload: '', // 图片上传后地址
				name: '', // 商品名称
				description: '', // 商品描述
				cateId: '', // 商品分类id
				cateName: '', // 商品分类名字
				price: '', // 商品价格
				boxPrice: '', // 餐盒费
				
				spLists: [], // 规格列表
				attLists: [], // 属性列表
			};
		},
		watch: {
			// 图片上传后地址
			upload(newValue, oldValue) {
				if (newValue) {
					// 上传完图片
					// 调用提交接口
					this.submit()
				}
			},
		},
		onLoad(options) {
			if (options.params) {
				let params = JSON.parse(options.params)
				this.type = 1
				uni.setNavigationBarTitle({
					title: '编辑商品'
				})
				this.id = params.id
				this.last = params.img
				this.image = params.img
				this.name = params.name
				if (params.description) this.description = params.description
				this.cateId = params.typeId
				this.cateName = params.typeName
				if (params.spLists.length) {
					this.spLists = this.deepClone(params.spLists)
				} else {
					this.price = params.defaultSpec.price
					this.boxPrice = params.defaultSpec.boxPrice
				}
				if (params.attLists.length) {
					this.attLists = this.deepClone(params.attLists)
				}
			} else {
				this.type = 0
				uni.setNavigationBarTitle({
					title: '新增商品'
				})
			}
			// 获取七牛上传使用TOKEN
			this.getUploadToken()
		},
		methods: {
			// 选择图片上传前的处理
			async selectUploadHandle() {
				this.image = await this.chooseSingelImage()
			},
			
			// 跳转选择商品分类管理
			goSelectGoodsCate() {
				uni.navigateTo({
					url: `/pages/subPackage/merchant/cate_manage/cate_manage?type=${1}`
				})
			},
			
			// 跳转规格管理
			goSpecManage() {
				uni.navigateTo({
					url: `/pages/subPackage/merchant/spec_manage/spec_manage?spLists=${JSON.stringify(this.spLists)}`
				})
			},
			
			// 跳转属性管理
			goAttrManage() {
				uni.navigateTo({
					url: `/pages/subPackage/merchant/attr_manage/attr_manage?attLists=${JSON.stringify(this.attLists)}`
				})
			},
			
			// 提交处理
			submitHandle() {
				if (!this.image) {
					return uni.showToast({
						icon: 'none',
						title: '未选择商品图片！'
					})
				} else if (!this.name) {
					return uni.showToast({
						icon: 'none',
						title: '未输入商品名称！'
					})
				} else if (!this.cateId) {
					return uni.showToast({
						icon: 'none',
						title: '未选择商品分类！'
					})
				} else if (!this.spLists.length && !this.price) {
					return uni.showToast({
						icon: 'none',
						title: '未输入价格或添加规格！'
					})
				} else if (!this.spLists.length && (!this.priceReg.test(this.price) || !this.priceReg.test(this.boxPrice))) {
					return uni.showToast({
						icon: 'none',
						title: '请检查价格或餐盒费格式！'
					})
				}
				
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				
				if (this.last == this.image) { // 没有进行图片修改
					this.upload = this.last
				} else { // 修改了图片
					// 上传学生证
					let pathArr = this.image.split('.')
					let extra = pathArr[pathArr.length-1]
					// 获得唯一标识码
					let uniqueCode = this.generateUUID()
					uni.uploadFile({
						url: 'https://up-z2.qiniup.com',
						filePath: this.image,
						name: 'file',
						formData: {
							'key': uniqueCode + '.' + extra,
							'token': this.qntoken,
						},
						success: (res) => {
							console.log('uni.uploadFile', res)
							let strToObj = JSON.parse(res.data)
							let backUrl = env.imageUrl + strToObj.key
							// 处理上传成功后的返回值
							this.upload = backUrl
						},
						fail: (err) => {
							console.log('uni.uploadFile', err)
							uni.hideLoading()
							uni.showToast({
								icon: 'none',
								title: '上传时出错，请检查网络后重试！'
							})
						}
					})
				}
			},
			
			// 提交接口
			submit() {
				let params = {}
				if (this.id) params['id'] = this.id
				params['img'] = this.upload
				params['name'] = this.name
				if (this.description) params['description'] = this.description
				params['typeId'] = this.cateId
				if (this.spLists.length) {
					params['spLists'] = this.spLists
				} else {
					params['price'] = this.price?Number(this.price):0
					params['boxPrice'] = this.boxPrice?Number(this.boxPrice):0
				}
				if (this.attLists.length) {
					params['attLists'] = this.attLists
				}
				
				this.$api.AddGoods(params).then(res => {
					console.log('AddGoods-success', res)
					uni.hideLoading()
					if (res.data.code == 200) {
						uni.navigateBack({
							delta: 1,
							success: () => {
								uni.showToast({
									icon: 'none',
									title: this.id?'修改成功！':'添加成功！'
								})
							}
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: res.data.msg
						})
					}
				}).catch(err => {
					console.log('AddGoods-fail', err)
					uni.hideLoading()
					uni.showToast({
						icon: 'none',
						title: this.id?'修改失败！':'添加失败！'
					})
				})
			},
		},
	}
</script>

<style lang="scss">

	// 信息项
	.info-grid {
		display: grid;
		grid-template-columns: 208rpx 1fr;
		align-items: center;
		border-bottom: 2rpx solid #f0f0f0;
		
		&.nb {
			border-bottom: none;
		}
		.row-box {
			height: 100%;
		}
		.image-box {
			width: 120rpx;
			height: 120rpx;
			position: relative;
			.image {
				display: block;
				width: 100%;
				height: 100%;
			}
			.close-box {
				height: fit-content;
				position: absolute;
				top: -20rpx;
				right: -20rpx;
			}
		}
	}
	// 同一高度
	.s-h {
		height: 94rpx;
	}
	// 底部border
	.bb {
		border-bottom: 2rpx solid #f0f0f0;
	}
</style>
